<template>

  <div id="app-container">
    <!-- 显示流步骤 -->
    <el-steps :active="2" align-center process-status="wait" style="margin-bottom: 40px">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>

  <div id="app-canvas">

    <el-form>
      <!-- 添加章节按钮 -->
      <el-button type="text" @click="openChapter"> 添加章节</el-button>

      <!-- 添加/修改 章节弹窗 -->
      <el-dialog title="添加章节" :visible.sync="dialogFormVisible">

        <el-form :model="chapter" label-width="120px">

          <el-form-item label="章节标题" :label-width="formLabelWidth">
            <el-input v-model="chapter.title"></el-input>
          </el-form-item>

          <el-form-item label="章节排序" :label-width="formLabelWidth">
            <el-input-number v-model="chapter.sort" :min="0" controls-position="right"></el-input-number>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        </div>
      </el-dialog>


      <el-form-item>
        <!-- 渲染章节 -->
        <ul class="chapterList">
          <li v-for="chapterVideo in chapterVideoList" :key=" chapterVideo.id">
            <p>
              {{ chapterVideo.title }}
              <span class="acts">
                <el-button type="text" @click="openAddVide(chapterVideo.id,chapter.courseId)">添加课时</el-button>


                <el-button style="" type="text" @click="editChapter(chapterVideo.id)">编辑</el-button>

                <el-popconfirm
                  confirm-button-text='确认'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除吗？"
                  @onConfirm="deleteChapter(chapterVideo.id)"
                >
                <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>

              </span>
            </p>

            <!-- 添加课时对话框 -->
            <el-dialog :visible.sync="dialogVideoFormVisible" title="添加课时">
              <el-form :model="video" label-width="120px">
                <el-form-item label="课时标题">
                  <el-input v-model="video.title"/>
                </el-form-item>
                <el-form-item label="课时排序">
                  <el-input-number v-model="video.sort" :min="0" controls-position="right"/>
                </el-form-item>
                <el-form-item label="是否免费">
                  <el-radio-group v-model="video.isFree">
                    <el-radio :label="1">免费</el-radio>
                    <el-radio :label="0">默认</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="上传视频">
                  <!-- TODO -->
                  <el-upload
                    :on-success="handleVodUploadSuccess"
                    :on-remove="handleVodRemove"
                    :before-remove="beforeVodRemove"
                    :on-exceed="handleUploadExceed"
                    :file-list="fileList"
                    :action="BASE_API + '/eduvod/video/uploadAliyunVideo'"
                    :limit="1"
                    field="file"
                    class="upload-demo"
                  >
                    <el-button size="small" type="primary">上传视频</el-button>
                    <el-tooltip placement="right-end">
                      <div slot="content">
                        最大支持1G，<br />
                        支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br />
                        GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br />
                        MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br />
                        SWF、TS、VOB、WMV、WEBM 等视频格式上传
                      </div>
                      <i class="el-icon-question" />
                    </el-tooltip>
                  </el-upload>

                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVideoFormVisible = false; fileList=[] ">取消</el-button>
                <el-button :disabled="saveVideoBtnDisabled" type="primary" @click="saveOrUpdateVideo">确定</el-button>
              </div>
            </el-dialog>

            <!--视频-->
            <ul class="chapterList videoList">
              <li
                v-for="video in chapterVideo.children" :key="video.id">
                <p>
                  {{ video.title }}
                  <span class="acts">
                      <el-button type="text" @click="openUpdateVide(video.id)">编辑</el-button>

                      <el-popconfirm
                        confirm-button-text='确认'
                        cancel-button-text='取消'
                        icon="el-icon-info"
                        icon-color="red"
                        title="确定删除吗？"
                        @onConfirm="deleteVideo(video.id)"
                      >
                      <el-button slot="reference" type="text" > 删除 </el-button>
                      </el-popconfirm>
                    </span>
                </p>
              </li>
            </ul>
          </li>
        </ul>
      </el-form-item>


      <el-form-item>
        <el-button @click="back()" style="margin: 0 4rem;" type="primary">回到上一步</el-button>
        <el-button @click="next()" type="primary">保存并下一步</el-button>
      </el-form-item>


    </el-form>
  </div>
  </div>
</template>

<script>
  import chapter from '@/api/edu/chapter'
  import video from '@/api/edu/video'

  export default {
    name: 'chapter',
    data() {
      return {
        chapterVideoList: [], // 获取到的章节及小结列表
        chapter: { // 表单内的值
          title: '', // 章节标题
          sort: 0,    // 章节排序
          courseId: 0 // 传递过来的课程 id
        },
        id: '', // 修改时使用的章节 id
        formLabelWidth: '120px', // 表单宽度
        dialogFormVisible: false, // 是否显示对话框
        // 添加小结相关配置
        dialogVideoFormVisible: false, // 是否显示小结对话框
        video: {
          title: '',
          sort: 0,
          isFree: 0,
          videoSourceId: '',
          chapterId: '', // 章节 id
          courseId: '' ,// 课程 id
          videoOriginalName:"" // 视频原始名称
        },
        saveVideoBtnDisabled: false,// 是否禁用
        fileList:[],// 要上传的文件列表
        BASE_API : process.env.VUE_APP_BASE_API
      }
    },
    methods: {
      // 上传成功之后的回调函数
      handleVodUploadSuccess(response,file,fileList){
        this.video.videoSourceId  = response.data.videoId
        // 在上传组件中，可以通过 file.name 来获取到上传的文件名
        this.video.videoOriginalName = file.name
      },
      // 删除的回调函数
      handleVodRemove(){
        video.deleteAlyVideo(this.video.videoSourceId).then(res=>{
          this.$message.success("删除成功")
          // 并且将文件列表也清楚
          this.fileList = []
          // 由于视频已经删除了，所以 video 里面的视频 id，视频名称也一样要清除
          this.video.videoSourceId  = ""
          // 删除视频名称
          this.video.videoOriginalName = ""
        })
      },
      // 删除之前的回调函数
      beforeVodRemove(file, fileList){
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      // 超出 limit上传个数的回调
      handleUploadExceed(file,fileList){
        this.$message.warning('想要重新上传视频，请先删除已上传的视频')
      },


      // 根据课程 id 获取章节和小节数据列表
      getChapterVideo() {
        chapter.getAllChapterVideo(this.chapter.courseId).then(res => {
          this.chapterVideoList = res.data.allChapterVideo
        })
      },
      // 下一步
      next() {
        if (this.$route.query.isList) {
          this.$router.push('/course/list')
        }else {
          this.$router.push('/course/save/publish/' + this.chapter.courseId)
        }
      },
      // 上一步
      back() {
        if (this.$route.query.isList) {
          this.$router.push('/course/list')
        }else {
          this.$router.push('/course/save/info/' + this.chapter.courseId)
        }
      },

      // 修改或者添加章节
      saveOrUpdate() {
        // 判断有没有 id 属性，有就是修改，没有就添加
        if (this.chapter.id) {
          this.SubmitEdit()
        } else {
          this.addChapter()
        }

      },
      // 打开章节对话框
      openChapter() {
        this.dialogFormVisible = true
        // 手动清空对话框内容，防止添加时显示，但是又不能去除课程 id ，因为后面要使用
        this.chapter.sort = 0
        this.chapter.title = ''
      },
      // 添加章节
      addChapter() {
        chapter.addChapter(this.chapter).then(res => {
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getChapterVideo()

        })
      },

      // 打开对话框，并且根据 id 回显 chapter（章节）
      editChapter(id) {
        chapter.getChapter(id).then(res => {
          this.dialogFormVisible = true
          // 这里查询到的，是章节的所有信息，所以可以直接赋值，里面包过课程 id
          this.chapter = res.data.chapter
        })
      },
      // 修改章节
      SubmitEdit() {
        chapter.updateChapter(this.chapter)
          .then(res => {
            // 刷新数据
            this.getChapterVideo()
            this.dialogFormVisible = false
            this.$message.success('修改成功')
            // 手动清空输入框内容，和赋值组件需要的值
            this.chapter = {}
            this.chapter.sort = 0
            this.chapter.courseId = this.$route.params.id
          })
      },

      // 删除章节
      deleteChapter(id) {
        chapter.deleteChapter(id).then(res => {
          // 刷新数据
          this.getChapterVideo()
          this.$message.success('删除成功')
        })
      },

      // 修改或者添加小结
      saveOrUpdateVideo() {
        if (this.video.id) {
          this.updateVide()
        } else {
          this.addVideo()
        }
      },
      // 小结的添加
      addVideo() {
        this.saveVideoBtnDisabled = true
        video.addVideo(this.video).then(res => {
          this.$message.success('添加成功')
          this.saveVideoBtnDisabled = false
          this.dialogVideoFormVisible = false
          this.getChapterVideo()
          this.fileList=[]
        })
      },
      // 打开小结添加框
      openAddVide(chapterId, courseId) {
        // 手动清楚上一次数据
        this.video.id = undefined
        this.video.title = ''
        this.video.sort = 0
        this.video.isFree = 0
        // 设置要添加的章节 id ，和课程 id
        this.dialogVideoFormVisible = true
        this.video.chapterId = chapterId
        this.video.courseId = courseId

      },

      // 打开修改小结对话框 ,传入小结 id 回显数据
      openUpdateVide(VideoId) {
        // 先清除上一次的数据
        video.getVideoById(VideoId).then(res => {
          // 将数据赋值给 video 进行显示
          this.video = res.data.video

          // 先进行判断，不然有 空白bug
          if (res.data.video.videoOriginalName){
            // 视频数据回显
            this.fileList = [{
              name: res.data.video.videoOriginalName,
              url: res.data.video.videoSourceId
            }]
          }

          this.dialogVideoFormVisible = true
        })
      },
      // 小结的修改
      updateVide() {
        video.updateVideo(this.video).then(res => {
          this.$message.success('修改成功')
          this.dialogVideoFormVisible = false
          this.getChapterVideo()
          this.fileList=[]
        })
      },

      // 删除小结
      deleteVideo(id) {
        video.deleteVideo(id).then(res => {
          // 刷新数据
          this.getChapterVideo()
          this.$message.success('删除成功')
        })
      }

    },
    created() {
      this.$store.dispatch('app/saveActive', 2)
      // 获取路由参数
      if (this.$route.params && this.$route.params.id) {
        this.chapter.courseId = this.$route.params.id
        // 调用方法，根据 id 获取到章节信息
        this.getChapterVideo()
      }

    }
  }
</script>

<style scoped>
  /* 设置组件位置 */
  #app-canvas {

    width: 400px;
    overflow: hidden;
    margin: 1px auto;
    position: static;
  }

  /* 自定义组件样式 */
  .chapterList {
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .chapterList li {
    position: relative;
  }

  .chapterList p {
    float: left;
    font-size: 20px;
    margin: 5px 0;
    padding: 10px;
    height: 60px;
    line-height: 50px;
    width: 100%;
    border: 1px solid #DDD;
  }

  .videoList {
    margin-left: 40px;
  }

  .acts {
    float: right;
  }

/* 设置上传按钮边上问号位置 */
  .upload-demo i{
    margin-left: 5px;
  }
</style>
